<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const tableList = ref<any[]>([])
const tableLoading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchTableName = ref('')

const fetchTableList = async () => {
  tableLoading.value = true
  try {
    const res = await request.get('/api/table/list', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        tableName: searchTableName.value
      }
    })
    tableList.value = res.data.records
    total.value = res.data.total
  } finally {
    tableLoading.value = false
  }
}

onMounted(() => {
  fetchTableList()
})

const genForm = reactive({
  table: null as any,
  types: ['entity', 'controller', 'service', 'serviceImpl', 'mapper', 'xml', 'vue-list', 'vue-form'],
  backendPath: '/d/java_project_all/excelTest/webAdminProject/src/main/java/com/jshan/modules',
  frontendPath: '/d/java_project_all/excelTest/webAdminProject/ops_web/src/views',
})

const typeOptions = [
  { label: 'Entity', value: 'entity' },
  { label: 'Controller', value: 'controller' },
  { label: 'Service', value: 'service' },
  { label: 'ServiceImpl', value: 'serviceImpl' },
  { label: 'Mapper', value: 'mapper' },
  { label: 'XML', value: 'xml' },
  { label: '前端列表页', value: 'vue-list' },
  { label: '前端表单页', value: 'vue-form' },
]

const previewDialog = ref(false)
const previewTabs = ref<string[]>([])
const previewCode = ref<Record<string, string>>({})
const previewLoading = ref(false)

const handlePreview = async () => {
  if (!genForm.table) {
    ElMessage.warning('请选择数据表')
    return
  }
  previewLoading.value = true
  try {
    const req = {
      tableName: genForm.table.tableName,
      tableComment: genForm.table.tableComment,
      fields: genForm.table.fields,
      indexes: genForm.table.indexes,
      types: genForm.types,
      backendPath: genForm.backendPath,
      frontendPath: genForm.frontendPath
    }
    // 获取表字段和索引（可扩展为后端接口）
    if (!req.fields) {
      // 简单模拟，实际应后端返回字段结构
      req.fields = [
        { name: 'id', type: 'bigint', comment: '主键' }
      ]
    }
    const res = await request.post('/api/codegen/preview', req)
    previewCode.value = res.data
    previewTabs.value = Object.keys(res.data)
    previewDialog.value = true
  } finally {
    previewLoading.value = false
  }
}

const handleGenerate = async () => {
  if (!genForm.table) {
    ElMessage.warning('请选择数据表')
    return
  }
  try {
    await ElMessageBox.confirm('确定要生成代码到指定目录吗？', '提示', { type: 'warning' })
    const req = {
      tableName: genForm.table.tableName,
      tableComment: genForm.table.tableComment,
      fields: genForm.table.fields,
      indexes: genForm.table.indexes,
      types: genForm.types,
      backendPath: genForm.backendPath,
      frontendPath: genForm.frontendPath
    }
    await request.post('/api/codegen/generate', req)
    ElMessage.success('生成成功！')
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('生成失败')
  }
}

const handleTableSelect = async (row: any) => {
  genForm.table = row
  // TODO: 可扩展为后端接口获取字段和索引
  genForm.table.fields = [
    { name: 'id', type: 'bigint', comment: '主键' }
  ]
  genForm.table.indexes = []
}
</script>

<template>
  <div class="app-container">
    <el-card>
      <div style="margin-bottom: 16px;">
        <el-input v-model="searchTableName" placeholder="表名" style="width: 200px; margin-right: 8px;" @keyup.enter="fetchTableList" />
        <el-button type="primary" @click="fetchTableList">搜索</el-button>
      </div>
      <el-table
        :data="tableList"
        v-loading="tableLoading"
        highlight-current-row
        @current-change="handleTableSelect"
        style="margin-bottom: 16px;"
      >
        <el-table-column prop="tableName" label="表名" width="180" />
        <el-table-column prop="tableComment" label="表注释" />
      </el-table>
      <el-form :model="genForm" label-width="120px" style="max-width: 700px;">
        <el-form-item label="生成类型">
          <el-checkbox-group v-model="genForm.types">
            <el-checkbox v-for="item in typeOptions" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="后端生成路径">
          <el-input v-model="genForm.backendPath" placeholder="如 /xxx/xxx/modules" />
        </el-form-item>
        <el-form-item label="前端生成路径">
          <el-input v-model="genForm.frontendPath" placeholder="如 /xxx/xxx/views" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePreview">预览代码</el-button>
          <el-button type="success" @click="handleGenerate">生成代码</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog v-model="previewDialog" title="代码预览" width="80vw" :close-on-click-modal="false">
      <el-tabs v-model="previewTabs[0]">
        <el-tab-pane v-for="tab in previewTabs" :key="tab" :label="tab">
          <el-input type="textarea" :rows="30" v-model="previewCode[tab]" readonly style="font-family: monospace;" />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="previewDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}
</style> 